package com.lemote.tag;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import com.lemote.entity.Permission;
import com.lemote.entity.User;

public class SecurityTag extends TagSupport {
	
	/**
	 * 权限控制标识
	 */
	private String authority;
	
	private HttpServletRequest request;
	
	private Set<Permission> permissions;

	@Override
	public int doEndTag() throws JspException {
		
		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		request = (HttpServletRequest) pageContext.getRequest(); 
		User user = (User) request.getSession().getAttribute("smt_user");
		if (permissions==null) {
			permissions = (Set<Permission>) request.getSession().getAttribute("permissions");
		}
		if (null == user||verify()) {
			return SKIP_BODY ;
		}
		return EVAL_PAGE;
	}
	
	public Boolean verify(){
		
		if (permissions!=null&&permissions.size()>0) {
			for (Permission permission : permissions) {
				if (authority!=null&&!"".equals(authority)) {
					return authority.equals(StringUtils.trim(permission.getEname()));
				}
			}
		}
		return false;
	}

	public String getAuthority() {
		return authority;
	}

	public void setAuthority(String authority) {
		this.authority = StringUtils.trim(authority);
	}

}
